package manet.gui;

import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javaclient2.structures.fiducial.PlayerFiducialItem;

import javax.swing.*;

import manet.Node;

/**
 * @author stra0556
 *
 */
public class RobotSimFrame {
	/**
	 * The default panel size to be used
	 */
	private static final Dimension PANEL_SIZE = new Dimension(800, 800);

	/** The outline color of the robot */
	private static Color OUTLINE_COLOR = Color.BLACK;

	private static JPanel mainPanel = new JPanel() {

		/** Boring serial number */
		private static final long serialVersionUID = 1L;


		/* (non-Javadoc)
		 * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
		 */
		protected void paintComponent(Graphics g){
			/* Call the typical paint then paint our robots */
			super.paintComponent(g);
			paintRobots(g);
		}
	};

	/**
	 * The list of all possible robots 
	 */
	private static List<Node> robotList = Collections.synchronizedList(new ArrayList<Node>());

	/** The size of the rectangle which represents the robot */
	final static int RECTANGLE_SIZE = 10;

	/**
	 * The default constructor for the robot simulation frame 
	 */
	public RobotSimFrame() {

		/* Set the initial panel size */
		mainPanel.setPreferredSize(PANEL_SIZE);
		mainPanel.setSize(PANEL_SIZE);

		/* Create the JFrame and add it */
		JFrame frame = new JFrame("Robot Simulation");
		frame.getContentPane().add(mainPanel);

		/* Set the close operation and set it to be visible */
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);

	} 

	public void updateGUI( List<Node> nodes){
		robotList = Collections.synchronizedList(new ArrayList<Node>( nodes ));
		getComponent().repaint();
	}

	/**
	 * @param g The graphic where the robot icons will be printed 
	 */
	private static void paintRobots( Graphics g ){

		for ( Node robot : robotList ) {

			/* Set the color for the outline */
			g.setColor( robot.getFillColor() );

			/* Figure out where the robot center is and draw a square */
			Point center = robot.getCoords();
			g.fillRect( center.x-RECTANGLE_SIZE/2, center.y - RECTANGLE_SIZE/2,  RECTANGLE_SIZE, RECTANGLE_SIZE );

			/* Draw the range of the robot */
			robot.getRange();
			Point upperLeft = robot.getUpperLeft();
			g.drawOval( upperLeft.x, upperLeft.y, robot.getRange() * 2, robot.getRange() * 2);
			
			/* Set the outline color and draw around */
			g.setColor( OUTLINE_COLOR );
			g.drawRect(center.x-RECTANGLE_SIZE/2, center.y - RECTANGLE_SIZE/2,  RECTANGLE_SIZE, RECTANGLE_SIZE );


			
			for ( PlayerFiducialItem neighbor : robot.getFiducialItems() ){

				/* Get the center points of the robots */
				Point c2 = robotList.get(neighbor.getId()-1).getCoords();

				/* Connect the dots */
				g.drawLine(center.x, center.y, c2.x, c2.y);

			}
		}


	}

	/**
	 * @return returns the main panel 
	 */
	public JComponent getComponent(){
		return mainPanel;
	}
}